package white_list

import (
	"bytes"
	"fmt"
	"net/http"
	"parking-lot-go-admin/config"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/cars"
	"time"

	"github.com/gin-gonic/gin"
)

func Delete(c *gin.Context) {
	requestDataStruct := struct {
		Id int `json:"id"`
	}{}

	c.ShouldBindJSON(&requestDataStruct)

	var carsWhiteListStruct cars.CarsWhiteListStruct
	var carsWhiteListData cars.CarsWhiteListStruct

	model.GetModelDataFirst(
		model.Db,
		carsWhiteListStruct.TableName(),
		&carsWhiteListData,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"id": requestDataStruct.Id,
			},
		})

	//解除车牌异步请求
	go func() {
		//拼接url
		systemSection := config.Cfg.Section("SYSTEM")
		url := systemSection.Key("INTERFACE_URL").String() + "artificial/un_bind"

		jsonData := []byte(
			fmt.Sprintf(`{"phone": "%s", "car_id": "%s", "car_no_color": "%d", "car_type": "%d"}`,
				carsWhiteListData.Mobile, carsWhiteListData.CarNumber, carsWhiteListData.CarNoColor, carsWhiteListData.CarType))

		//发送请求
		resp, _ := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		defer resp.Body.Close()
	}()

	//删除记录
	model.UpdateModelData(
		model.Db,
		carsWhiteListStruct.TableName(),
		map[string]interface{}{
			"id": requestDataStruct.Id,
		},
		map[string]interface{}{
			"deleted_at": time.Now(),
		},
	)

	controller.Success(c, "")
}
